package learn.sec;

import net.sf.json.JSONObject;
import org.apache.commons.codec.binary.Base64;

/**
 * Created By  醉美柳舞之众星捧月
 *
 * @author 宋贤坤
 * @date 2019/6/13 18:46
 */
public class WXCore {

    private static final String WATERMARK = "watermark";
    private static final String APPID = "wx8a4575c2cbfdb4b2";


    public static String decrypt(String appId, String encryptedData, String sessionKey, String iv) {
        String result = "";
        try {
            AesOthers aes = new AesOthers();
            byte[] resultByte = aes.decrypt(Base64.decodeBase64(encryptedData), Base64.decodeBase64(sessionKey), Base64.decodeBase64(iv));
            if (null != resultByte && resultByte.length > 0) {
                result = new String(WxPKCS7Encoder.decode(resultByte));
                JSONObject jsonObject = JSONObject.fromObject(result);
                String decryptAppid = jsonObject.getJSONObject(WATERMARK).getString(APPID);
                if (!appId.equals(decryptAppid)) {
                    result = "";
                }
            }
        } catch (Exception e) {
            result = "";
            e.printStackTrace();
        }
        return result;
    }


    public static void main(String[] args) throws Exception {
        String appId = "wx8a4575c2cbfdb4b2";
        String encryptedData = "lt6Q1qbDAxFDwgU7cV1N7aJUCyAzKVhi5cP9aPotnXsIK7JpG4O8E7qghM1n8AGmL8PLS1R0CXm2OZoBE6py8ZtXLM+ZfjBJpYOU9/NIZc2PRdh+GnJcGEgVAWf2q4fy2dgLuwbzF/rwzH/8cWHtaM/hn9jnEXiGGLZ068gqG0jrwco6mjmxLXMf7O6E/kdJ+zXiBduX7thC5KvEW99nWgJt434lbXNEMa0bKE/zNpN03A18XWuQK9Ofy7EBg+2T4FCq7rxSaYBZAYNKObUwKBzr+dovJf09tJOx5tkBXTzQDS+12BWEOCLsvpeEZ47AyNG5n6BNhbcBfQ1oOF1oiUyM8uzzW61GMstztxgC3YQOAF4WybWRTQnEtikzv56brV2BmLx88E1Fk+W8dsydRSnSlMBiPWh406SqPqDeK5Pdw29/vebnkuPL0OxWEO6f6jHp0WmQgz/Wj2c84+WcADoyiSMkyIHNxQd+6a7ntGE=";
        String sessionKey = "ltNwq7RkQUiT+yPK1L4GlA==";
        String iv = "WELOy1iDdxKX7xwsvtO2FQ==";
        System.out.println(decrypt(appId, encryptedData, sessionKey, iv));
    }
}